import React, {useEffect, useState} from 'react';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {
  ProForm,
  ProFormSelect,
  ProFormText, ProFormTextArea
} from "@ant-design/pro-form";
import styles from './style.less';
import {Card, Col, Form, message, Row} from "antd";
import {Marketing} from "@/services/api-functions";
import UploadForm from "@/components/UploadForm";
import {ContentModRequest, OssPojo} from "@/services/api-types";
// @ts-ignore
import {history} from "umi";
import {SYS_ENUMS} from "@/utils/constants";
import RichEditor from "@/components/RichEditor";


export const contentSaveOrUpdate = async (fields: any, select: any, longInfo: string, cover: OssPojo|undefined) => {
  try {
    const rpo: ContentModRequest = {
      id: select?.id ?? '',
      cover,
      title: fields.title,
      name: fields.name,
      type: fields.type,
      jumpType: fields.jumpType,
      jumpKey: fields.jumpKey,
      longInfo: fields.longInfo??longInfo,
      // worksContentSize: richWordsNum(content)
    }
    if (isSuccess((select && select.id ? (await Marketing.contentEdit(rpo)) : (await Marketing.contentAdd(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

const ContentEdit: React.FC<any> = ({match: {params: {id}}}) => {

  const [formRef] = Form.useForm()
  const [type, setType] = useState<any>(undefined)
  const [content, setContent] = useState<any>(null);
  const [cover, setCover] = useState<OssPojo>();
  const [html, setHtml] = useState<any>() // 存储 editor 实例


  const queryContentDetail = (contentId: any) => {
    if (contentId) {
      Marketing.contentDetail(contentId).then(({code, data}) => {
        if (isSuccess(code)) {
          setContent(data)
          if (data.cover) {
            setCover(data.cover)
          }
          if (data.type) {
            setType(data.type)
          }
          // setEditorState(BraftEditor.createEditorState(data?.content ?? ''))
          if(data.type === 'WEB_VIEW'){
            setHtml(data?.longInfo ?? '')
          }

          formRef?.setFieldsValue({
            name: data.name,
            title: data.title,
            cover: data.cover ? [data.cover] : [],
            type: data.type,
            jumpKey: data.jumpKey,
            jumpType: data.jumpType,
            longInfo: data.longInfo,
          })
        }
      })
    }
  }

  useEffect(() => {
    queryContentDetail(id)
  }, [id])

  const onFinish = async (values: Record<string, any>) => {
    if (await contentSaveOrUpdate(values, content, html ?? '', cover)) {
      history.push('/marketing/content/list')
    }
  };

  return (
    <ProForm
      layout="vertical"
      hideRequiredMark
      submitter={{render: (props, dom) =><FooterToolbar>{dom}</FooterToolbar>,}}
      form={formRef}
      initialValues={{}}
      onFinish={onFinish}
      onValuesChange={v => {
        if(v.type){
          setType(v.type)
        }
      }}
    >
      <PageContainer>
        <Card title={`${id?'编辑':'添加'}内容`} className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormText label='名称' required rules={[{required: true, message: '请填写名称',},]} name="name"/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormText label='标题' required rules={[{required: true, message: '请填写标题',},]} name="title"/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect label='内容类型' required rules={[{required: true, message: '请填选择内容类型',},]} name='type'
                             initialValue={'NOTHING'}
                             options={Object.values(SYS_ENUMS.CONTENT_TYPE)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm label='封面' name='cover' type='public' max={1}
                          rules={type === SYS_ENUMS.CONTENT_TYPE.NOTICE.value ? [] : [{
                            required: true,
                            message: '请上传封面',
                          },]} required={type !== SYS_ENUMS.CONTENT_TYPE.NOTICE.value}
                          accept='.jpg,.jpeg,.bmp,.gif,.png' success={file => setCover(file)}
                          remove={() => setCover(undefined)}/>
            </Col>
          </Row>
          {
            type === SYS_ENUMS.CONTENT_TYPE.JUMP_PAGE.value && <Row gutter={16}>
              <Col lg={6} md={12} sm={24}>
                <ProFormSelect label='跳转类型' required rules={[{required: true, message: '请填选择跳转类型',},]} name='jumpType'
                               initialValue={'RESOURCES'}
                               options={Object.values(SYS_ENUMS.JUMP_TYPE)}/>
              </Col>
            </Row>
          }
          {
            type === SYS_ENUMS.CONTENT_TYPE.JUMP_PAGE.value && <Row gutter={16}>
              <Col lg={12} md={12} sm={24}>
                <ProFormText label='跳转业务数据' name="jumpKey"/>
              </Col>
            </Row>
          }
          {
            type === SYS_ENUMS.CONTENT_TYPE.NOTICE.value && <Row gutter={16}>
              <Col lg={12} md={12} sm={24}>
                <ProFormTextArea label='公告内容' name="longInfo"/>
              </Col>
            </Row>
          }
          {
            type === SYS_ENUMS.CONTENT_TYPE.WEB_VIEW.value && <Row gutter={16}>
              <Col lg={12} md={12} sm={24}>
                <Form.Item label='富文本内容' required>
                  <RichEditor onChange={(h: any)=>{setHtml(h)}} initValue={content?.longInfo??''} />
                </Form.Item>
              </Col>
            </Row>
          }
        </Card>
      </PageContainer>
    </ProForm>
  );
};

export default ContentEdit;
